package com.zhongwang.mms.module.half.service;

import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.BReportPlan;
import com.zhongwang.mms.gen.entity.HInventory;
import com.zhongwang.mms.module.half.dao.HChangeOrderDao;
import com.zhongwang.mms.module.half.dao.HInventoryDao;
import com.zhongwang.mms.module.half.model.HChangeOrderModel;
import com.zhongwang.mms.module.purchase.model.ChangeOrderQueryModel;
import com.zhongwang.mms.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @description:串料执行
 * @author: th
 * @time: 2020/5/5 15:34
 */
@Log4j2
@Service
public class ChangeExcService {

    @Autowired
    private HChangeOrderDao hChangeOrderDao;
    @Autowired
    private HInventoryDao hInventoryDao;

    /**
     * @param queryModel
     * @return
     */
    public List<HChangeOrderModel> selectChangeOrderListByQuery(ChangeOrderQueryModel queryModel) {

        return hChangeOrderDao.selectChangeOrderExcListByQuery(queryModel);
    }

    /**
     * 串料执行
     *
     * @param hChangeOrderModel
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult execApply(HChangeOrderModel hChangeOrderModel) {
        JsonResult jsonResult = new JsonResult();
        List<HChangeOrderModel> hChangeOrders = hChangeOrderDao.getAllByPrimarys(hChangeOrderModel.getCeoIds());
        for (int i = 0; i < hChangeOrders.size(); i++) {
            HChangeOrderModel hChangeOrder = hChangeOrders.get(i);
            HInventory hInventory = hInventoryDao.selectAllById(hChangeOrder.getCeoUseItyId());
            if (hInventory.getItyNum() < hChangeOrder.getCeoNeedNum()) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("因库存数量不足，请驳回！");
                return jsonResult;
            }
        }
        for (int i = 0; i < hChangeOrders.size(); i++) {
            HChangeOrderModel hChangeOrder = hChangeOrders.get(i);
            HInventory hInventory = hInventoryDao.selectAllById(hChangeOrder.getCeoUseItyId());
            //插入串过来库存的数据
            //hInventory.setItyMatName(hChangeOrder.getCeoNeedMatName());
            hInventory.setItyProCode(hChangeOrder.getCeoNeedProCode());
            hInventory.setItyProName(hChangeOrder.getCeoNeedProName());
            hInventory.setItyNum(hChangeOrder.getCeoNeedNum());
            hInventory.setItyAvaNum(hChangeOrder.getCeoNeedNum());
            hInventory.setItyStockType(2);
            hInventoryDao.insert(hInventory);
            //反写使用的库存信息到串料数据中,等待提报计划指定。
            hChangeOrder.setCeoNeedItyId(hInventory.getItyId());
            hChangeOrder.setCeoAppyStatus(3);
            hChangeOrder.setCeoStatus(1);
            hChangeOrder.setCeoAuditorId(ShiroUtils.getUser().getId());
            hChangeOrder.setCeoAuditDate(new Date());
            hChangeOrderDao.updateSelective(hChangeOrder);
            //获取原库存数据并更改其值为,库存数量为可用数量。
            hInventory = hInventoryDao.selectAllById(hChangeOrder.getCeoUseItyId());
            hInventory.setItyNum(hInventory.getItyNum() - hChangeOrder.getCeoNeedNum());
            //执行时不需要更改可用数量
            //hInventory.setItyAvaNum(hInventory.getItyAvaNum() - hChangeOrder.getCeoNeedNum());
            hInventory.setItyStockType(2);
            hInventoryDao.updateByPrimaryKeySelective(hInventory);
        }
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
        jsonResult.setMsg("执行成功！");
        return jsonResult;
    }

    /**
     * 驳回串料申请
     *
     * @param hChangeOrderModel
     * @return
     */
    @Transactional
    public boolean remove(HChangeOrderModel hChangeOrderModel) {

        try {
            /*//获取申请列表，往回标记库存
            List<HChangeOrderModel> hChangeOrders = hChangeOrderDao.getAllByPrimarys(hChangeOrderModel.getCeoIds());
            for (int i = 0; i < hChangeOrders.size(); i++) {
                HInventory hInventory = hInventoryDao.selectAllById(hChangeOrders.get(i).getCeoUseItyId());
                hInventory.setItyAvaNum(hInventory.getItyAvaNum() + hChangeOrders.get(i).getCeoNeedNum());
                hInventoryDao.updateByPrimaryKeySelective(hInventory);
            }*/
            hChangeOrderDao.updateStatusByPrimarys(hChangeOrderModel.getCeoIds());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 撤销
     *
     * @param hChangeOrderModel
     * @return
     */
    @Transactional
    public boolean revokeApply(HChangeOrderModel hChangeOrderModel) {
        try {
            List<HChangeOrderModel> hChangeOrderModelList = hChangeOrderDao.getAllByPrimarys(hChangeOrderModel.getCeoIds());
            //检测所有申请是否已经出库或被串料，如何验证出库，即串料之后的新库存数据可用数量或者库存数量小于串料数量则不可撤销
            for (HChangeOrderModel hChangeOrder : hChangeOrderModelList) {
                //如果已出库则无法撤销
                 if (hChangeOrder.getCeoStatus().equals(2)) {
                    return false;
                }
                //获取因串料新生成的数据
                HInventory hInventory = hInventoryDao.selectAllById(hChangeOrder.getCeoNeedItyId());
                if(hInventory.getItyNum() < hChangeOrder.getCeoNeedNum()){
                    return false;
                }
                //如果被执行项目化库存则不可撤销
                if (hInventory.getItyStockType().equals(1)) {
                    return false;
                }
                //如果发现因出库、标记造成的库存数量或可用数量无法撤销则返回假
                /*if (hInventory.getItyNum() < hChangeOrder.getCeoNeedNum() ||
                        hInventory.getItyAvaNum() < hChangeOrder.getCeoNeedNum()) {
                    return false;
                }*/
            }
            //更改库存
            //首先获取串料实体类
            for (int i = 0; i < hChangeOrderModelList.size(); i++) {
                HChangeOrderModel hChangeOrderModel1 = hChangeOrderModelList.get(i);

                //获取串料生成的库存，清零0库存
                HInventory ceoNeedHInventory = hInventoryDao.selectAllById(hChangeOrderModel1.getCeoNeedItyId());
                ceoNeedHInventory.setItyNum(0d);
                ceoNeedHInventory.setItyAvaNum(0d);
                hInventoryDao.updateHInventoryAvaNumByPrimary(ceoNeedHInventory);
                //获取被串料的库存，回写增加被串料的数量
                HInventory ceoUsePInventory = hInventoryDao.selectAllById(hChangeOrderModel1.getCeoUseItyId());
                ceoUsePInventory.setItyNum(ceoUsePInventory.getItyNum() + hChangeOrderModel1.getCeoNeedNum());
                //ceoUsePInventory.setItyAvaNum(ceoUsePInventory.getItyAvaNum() + hChangeOrderModel1.getCeoNeedNum());
                hInventoryDao.updateHInventoryAvaNumByPrimary(ceoUsePInventory);
                //如果被制定计划,则清除指定计划的标记状态为0
                if (hChangeOrderModel1.getCeoRppId() != null && hChangeOrderModel1.getCeoRppId() != 0) {
                    BReportPlan bReportPlan = hChangeOrderDao.getBReportPlanPrimaryKey(hChangeOrderModel1.getCeoRppId());
                    bReportPlan.setRppIsFlag(0);
                    hChangeOrderDao.updateBReportPlanRppIsFlagByPrimaryKey(bReportPlan);
                }
                //作废此串料单：清空标记计划ID为0，申请状态为作废。
                hChangeOrderModel1.setCeoRppId(0);
                hChangeOrderModel1.setCeoAppyStatus(2);
                hChangeOrderDao.updateSelective(hChangeOrderModel1);

                //logService.saveLog("【外购件】撤销串料申请","撤销的串料单编号："+hChangeOrderModel1.getCeoCode());

            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }
}
